# -*- coding: utf-8 -*-
"""
Created on Fri Dec 21 18:55:04 2012

@author: Winand
"""
import os
from Cookie import BaseCookie
from settings import ROOTDIR
#import ConfigParser

class CookieWrapper(BaseCookie):
    def output(self):
        return super(CookieWrapper, self).output(header='\0', sep='' \
                                                ).strip('\0 ').split('\0 ')
                                                
    def get_val(self, key, default=None):
        v=self.get(key)
        return v.value if v else default

#re-encode string from /cp/ codepage to utf-8
def str8(s, cp):
    return s.decode(cp).encode('utf-8')

#Convert relative path to normalized absolute path
def localPath(rel):
    return os.path.join(ROOTDIR, os.path.normpath(rel).lstrip(os.sep))
    
#dot notation dictionary
class ddict(dict):
    def __getattr__(self, attr):
        return self.get(attr, None)
    __setattr__= dict.__setitem__
    __delattr__= dict.__delitem__

#test if dict includes all keys
def hasKeys(dat, keys):
    if type(keys) is not tuple: keys=(keys,)
    if dat and type(keys) is tuple and set(keys)<=set(dat):
        return True

#TODO: Think more of this. )
#strip html tags, escape &
from HTMLParser import HTMLParser
class HtmlProcessor(HTMLParser):
    def __init__(self):
        self.reset()
        self.fed = []
    def handle_charref(self, number):
        self.fed.append("&#%s;" % number)
    def handle_entityref(self, name):
        self.fed.append("&%s;" % name)
    def handle_data(self, d):
        self.fed.append(d.replace("&", "&amp;"))
    def get_data(self):
        return ''.join(self.fed)
    @staticmethod
    def toSafeText(html):
        s = HtmlProcessor()
        s.feed(html)
        return s.get_data()
        
from settings import SHARED_SERVER_ADDR, SHARED_SERVER_PORT
from webapi.server.socketpipe import SocketPipe
ANSWER_OK = 1
def makeBackgroundCall(mod, kwargs):
    sockpipe=SocketPipe()
    sockpipe.connect(SHARED_SERVER_ADDR, SHARED_SERVER_PORT)
    if sockpipe.send(("srv_callback", mod, kwargs)) != ANSWER_OK:
        return False
    sockpipe.close()
    return True

if __name__ == "__main__":
    cookie = CookieWrapper()
    cookie["cook"] = 123456
    cookie["cook"]["path"] = "\\"
    print cookie.output(), type(cookie["cook"])
    